const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const User = require('../models/User');

module.exports = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      throw new Error('未提供认证令牌');
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    if (!decoded.userId) {
      throw new Error('无效的认证令牌');
    }

    // 获取用户信息
    const user = await User.findById(decoded.userId);
    if (!user) {
      throw new Error('用户不存在');
    }

    // 设置用户信息到请求对象
    req.userId = decoded.userId;
    req.user = {
      _id: user._id,
      username: user.username,
      email: user.email,
      role: user.role || 'user'
    };

    next();
  } catch (error) {
    console.error('认证错误:', error);
    res.status(401).json({ 
      message: '请先登录',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
}; 